<template>
  <div class="contract-container">
    <el-card class="contract-header">
      <template #header>
        <div class="card-header">
          <span>员工合同</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增合同
          </el-button>
        </div>
      </template>

      <el-form :inline="true" :model="queryForm" class="search-form">
        <el-form-item label="员工姓名">
          <el-input v-model="queryForm.employee_name" placeholder="请输入员工姓名" clearable />
        </el-form-item>
        <el-form-item label="合同类型">
          <el-select v-model="queryForm.contract_type" placeholder="请选择合同类型" clearable>
            <el-option label="劳动合同" value="劳动合同" />
            <el-option label="实习协议" value="实习协议" />
            <el-option label="劳务合同" value="劳务合同" />
            <el-option label="保密协议" value="保密协议" />
          </el-select>
        </el-form-item>
        <el-form-item label="合同状态">
          <el-select v-model="queryForm.status" placeholder="请选择合同状态" clearable>
            <el-option label="有效" value="有效" />
            <el-option label="到期" value="到期" />
            <el-option label="终止" value="终止" />
            <el-option label="解除" value="解除" />
          </el-select>
        </el-form-item>
        <el-form-item label="到期日期">
          <el-date-picker
            v-model="queryForm.expire_date_range"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="contract-content">
      <el-table :data="tableData" style="width: 100%" height="calc(100vh - 330px)">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="employee_name" label="员工姓名" />
        <el-table-column prop="department_name" label="部门" />
        <el-table-column prop="position_name" label="职位" />
        <el-table-column prop="contract_type" label="合同类型" />
        <el-table-column prop="start_date" label="开始日期" />
        <el-table-column prop="end_date" label="结束日期" />
        <el-table-column prop="salary" label="薪资" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.limit"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      @close="handleDialogClose"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="员工" prop="employee_id">
              <el-select v-model="formData.employee_id" placeholder="请选择员工" filterable>
                <el-option
                  v-for="emp in employees"
                  :key="emp.id"
                  :label="emp.name"
                  :value="emp.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同类型" prop="contract_type">
              <el-select v-model="formData.contract_type" placeholder="请选择合同类型">
                <el-option label="劳动合同" value="劳动合同" />
                <el-option label="实习协议" value="实习协议" />
                <el-option label="劳务合同" value="劳务合同" />
                <el-option label="保密协议" value="保密协议" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始日期" prop="start_date">
              <el-date-picker
                v-model="formData.start_date"
                type="date"
                placeholder="选择开始日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="end_date">
              <el-date-picker v-model="formData.end_date" type="date" placeholder="选择结束日期" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="试用期(月)" prop="probation_months">
              <el-input-number v-model="formData.probation_months" :min="0" :max="12" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="薪资" prop="salary">
              <el-input-number v-model="formData.salary" :min="0" :precision="2" :step="500" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="工作地点" prop="work_location">
          <el-input v-model="formData.work_location" placeholder="请输入工作地点" />
        </el-form-item>
        <el-form-item label="工作内容" prop="job_description">
          <el-input
            v-model="formData.job_description"
            type="textarea"
            :rows="3"
            placeholder="请输入工作内容描述"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Plus, Search, Refresh } from '@element-plus/icons-vue'
  import type { FormInstance, FormRules } from 'element-plus'
  import { contractApi } from '@/api/user/contract'
  import { userApi } from '@/api/user'

  interface Contract {
    id: number
    employee_id: number
    employee_name: string
    department_name: string
    position_name: string
    contract_type: string
    start_date: string
    end_date: string
    probation_months: number
    salary: number
    work_location: string
    job_description: string
    status: string
    remark: string
  }

  interface Employee {
    id: number
    name: string
    department_name?: string
    position_name?: string
    department?: string
    position?: string
  }

  const queryForm = reactive({
    employee_name: '',
    contract_type: '',
    status: '',
    expire_date_range: [] as string[],
  })

  const tableData = ref<Contract[]>([])
  const employees = ref<Employee[]>([])

  const pagination = reactive({
    page: 1,
    limit: 10,
    total: 0,
  })

  const dialogVisible = ref(false)
  const dialogTitle = ref('')
  const submitLoading = ref(false)
  const formRef = ref<FormInstance>()

  const formData = reactive({
    id: undefined as number | undefined,
    employee_id: undefined as number | undefined,
    contract_type: '',
    start_date: '',
    end_date: '',
    probation_months: 3,
    salary: 0,
    work_location: '',
    job_description: '',
    remark: '',
  })

  const rules: FormRules = {
    employee_id: [{ required: true, message: '请选择员工', trigger: 'change' }],
    contract_type: [{ required: true, message: '请选择合同类型', trigger: 'change' }],
    start_date: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
    end_date: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
    probation_months: [{ required: true, message: '请输入试用期', trigger: 'blur' }],
    salary: [{ required: true, message: '请输入薪资', trigger: 'blur' }],
    work_location: [{ required: true, message: '请输入工作地点', trigger: 'blur' }],
  }

  const getStatusType = (status: string) => {
    const types: Record<string, string> = {
      有效: 'success',
      到期: 'warning',
      终止: 'danger',
      解除: 'info',
    }
    return types[status] || 'info'
  }

  const loadContractList = async () => {
    try {
      const params: any = {
        ...queryForm,
        page: pagination.page,
        limit: pagination.limit,
      }

      if (queryForm.expire_date_range && queryForm.expire_date_range.length === 2) {
        params.start_date = queryForm.expire_date_range[0]
        params.end_date = queryForm.expire_date_range[1]
      }

      const res = await contractApi.getList(params)
      if (res.code === 0) {
        tableData.value = res.data.list
        pagination.total = res.count || 0
      }
    } catch (error) {
      console.error('加载合同列表失败:', error)
    }
  }

  const loadEmployees = async () => {
    try {
      const res = await userApi.getUserList({ page: 1, limit: 1000 })
      if (res.code === 0) {
        employees.value = res.data.list.map((user: any) => ({
          id: user.id,
          name: user.name || user.username,
          department: user.department,
          department_name: user.department_name || user.department,
          position_name: user.position_name || user.position,
        }))
      }
    } catch (error) {
      console.error('加载员工列表失败:', error)
    }
  }

  const handleSearch = () => {
    pagination.page = 1
    loadContractList()
  }

  const handleReset = () => {
    queryForm.employee_name = ''
    queryForm.contract_type = ''
    queryForm.status = ''
    queryForm.expire_date_range = []
    handleSearch()
  }

  const handleAdd = () => {
    dialogTitle.value = '新增合同'
    dialogVisible.value = true
  }

  const handleEdit = (row: Contract) => {
    dialogTitle.value = '编辑合同'
    Object.assign(formData, {
      id: row.id,
      employee_id: row.employee_id,
      contract_type: row.contract_type,
      start_date: row.start_date,
      end_date: row.end_date,
      probation_months: row.probation_months,
      salary: row.salary,
      work_location: row.work_location,
      job_description: row.job_description,
      remark: row.remark,
    })
    dialogVisible.value = true
  }

  const handleView = (row: Contract) => {
    ElMessage.info(`查看 ${row.employee_name} 的合同详情`)
  }

  const handleDelete = async (row: Contract) => {
    try {
      await ElMessageBox.confirm('确定要删除该合同吗？', '提示', {
        type: 'warning',
      })
      const res = await contractApi.delete(row.id)
      if (res.code === 0) {
        ElMessage.success('删除成功')
        loadContractList()
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除合同失败:', error)
      }
    }
  }

  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      submitLoading.value = true

      const api = formData.id ? contractApi.edit : contractApi.add
      const res = await api(formData)

      if (res.code === 0) {
        ElMessage.success(formData.id ? '编辑成功' : '新增成功')
        dialogVisible.value = false
        loadContractList()
      }
    } catch (error) {
      console.error('提交失败:', error)
    } finally {
      submitLoading.value = false
    }
  }

  const handleDialogClose = () => {
    if (formRef.value) {
      formRef.value.resetFields()
    }
    Object.assign(formData, {
      id: undefined,
      employee_id: undefined,
      contract_type: '',
      start_date: '',
      end_date: '',
      probation_months: 3,
      salary: 0,
      work_location: '',
      job_description: '',
      remark: '',
    })
  }

  const handleSizeChange = (val: number) => {
    pagination.limit = val
    loadContractList()
  }

  const handleCurrentChange = (val: number) => {
    pagination.page = val
    loadContractList()
  }

  onMounted(() => {
    loadContractList()
    loadEmployees()
  })
</script>

<style scoped lang="scss">
  .contract-container {
    padding: 20px;
  }

  .contract-header {
    margin-bottom: 20px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-form {
    margin-top: 20px;
  }

  .contract-content {
    .el-pagination {
      margin-top: 20px;
      justify-content: flex-end;
    }
  }
</style>
